<template>
  <div class="admin-layout">
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="240px" class="sidebar">
        <div class="logo">
          <h3>视频管理系统</h3>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-dark"
          router
        >
          <el-menu-item index="/dashboard">
            <el-icon><Document /></el-icon>
            <span>仪表盘</span>
          </el-menu-item>
          <el-menu-item index="/categories">
            <el-icon><Menu /></el-icon>
            <span>视频类别管理</span>
          </el-menu-item>
          <el-menu-item index="/video-types">
            <el-icon><VideoCamera /></el-icon>
            <span>视频类型管理</span>
          </el-menu-item>
          <el-menu-item index="/videos">
            <el-icon><VideoPlay /></el-icon>
            <span>视频管理</span>
          </el-menu-item>
          <el-menu-item index="/comments">
            <el-icon><ChatRound /></el-icon>
            <span>评论管理</span>
          </el-menu-item>
          <el-menu-item index="/users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="/settings">
            <el-icon><Setting /></el-icon>
            <span>系统设置</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 主内容区 -->
      <el-container>
        <!-- 顶部导航 -->
        <el-header class="header">
          <div class="header-left">
            <span>管理员控制台</span>
          </div>
          <div class="header-right">
            <span class="user-info">{{ userInfo.username }}</span>
            <el-button type="text" @click="handleLogout">
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-button>
          </div>
        </el-header>

        <!-- 内容区 -->
        <el-main class="main-content">
          <div class="management-content">
            <h2>视频类型管理</h2>
            <div class="section-title">管理现有的视频类型</div>
            
            <div class="search-bar">
              <el-input
                v-model="searchQuery"
                placeholder="搜索类型名称或描述"
                prefix-icon="el-icon-search"
                style="width: 400px;"
              ></el-input>
              <el-button type="primary" @click="handleAddVideoType">
                <el-icon><Plus /></el-icon>
                添加视频类型
              </el-button>
            </div>

            <!-- 加载状态 -->
            <el-skeleton v-if="loading" :rows="8" animated />
            
            <!-- 类型列表 -->
            <div v-else class="video-types-grid">
              <el-card
                v-for="videoType in filteredVideoTypes"
                :key="videoType.type_id"
                class="video-type-card"
                :body-style="{ padding: '20px' }"
              >
                <div class="video-type-header">
                  <div class="video-type-title">
                    <h3>{{ safeGetProp(videoType, 'name', '未命名类型') }}</h3>
                  </div>
                  <el-dropdown trigger="click" @click.stop>
                    <el-button type="text" size="small" class="menu-button">
                      <el-icon><More /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="handleEditVideoType(videoType)" :disabled="false">编辑</el-dropdown-item>
                        <el-dropdown-item @click="handleDeleteVideoType(videoType)" danger :disabled="false">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div class="video-type-description">
                  {{ safeGetProp(videoType, 'description', '') }}
                </div>
                <div class="video-type-footer">
                  <span class="created-date">{{ formatDate(safeGetProp(videoType, 'created_at', new Date().toISOString())) }}</span>
                  <span class="updated-date">{{ formatDate(safeGetProp(videoType, 'updated_at', new Date().toISOString())) }}</span>
                </div>
              </el-card>
              
              <!-- 空状态 -->
              <div v-if="videoTypes.length === 0" class="empty-state">
                <el-empty description="暂无视频类型数据" />
              </div>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 添加/编辑视频类型对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingVideoType.type_id ? '编辑视频类型' : '添加视频类型'"
      width="500px"
    >
      <el-form
        ref="videoTypeFormRef"
        :model="editingVideoType"
        :rules="videoTypeRules"
        label-width="80px"
      >
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="editingVideoType.name" placeholder="请输入视频类型名称" />
        </el-form-item>
        <el-form-item label="类型描述" prop="description">
          <el-input
            v-model="editingVideoType.description"
            placeholder="请输入视频类型描述"
            type="textarea"
            rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveVideoType">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { Document, User, Menu, VideoPlay, ChatRound, Setting, SwitchButton, Plus, More, VideoCamera } from '@element-plus/icons-vue';
import { videoTypeService } from '../api/videoTypeService';

// 定义视频类型接口
interface VideoType {
  type_id: number;
  name: string;
  description: string;
  created_at: string;
  updated_at: string;
}

const router = useRouter();
const userInfo = ref({ username: '', nickname: '', role: '' });
const searchQuery = ref('');
const videoTypes = ref<VideoType[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const videoTypeFormRef = ref<FormInstance>();

// 编辑中的视频类型
const editingVideoType = reactive<Partial<VideoType>>({
  type_id: undefined,
  name: '',
  description: ''
});

// 表单验证规则
const videoTypeRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入视频类型名称', trigger: 'blur' },
    { min: 1, max: 50, message: '类型名称长度在 1 到 50 个字符', trigger: 'blur' }
  ]
});

const activeMenu = computed(() => {
  return window.location.pathname;
});

const filteredVideoTypes = computed(() => {
  if (!searchQuery.value) return videoTypes.value;
  
  const query = searchQuery.value.toLowerCase();
  return videoTypes.value.filter(videoType => 
    safeGetProp(videoType, 'name', '').toLowerCase().includes(query) || 
    safeGetProp(videoType, 'description', '').toLowerCase().includes(query)
  );
});

/**
 * 解析可能是JSON字符串的值，确保正确解析并返回文本内容
 * @param value 原始值
 * @param defaultValue 默认值
 * @returns 清理后的值
 */
const parseJsonValue = (value: any, defaultValue: string): string => {
  if (!value && value !== 0) return defaultValue;
  
  try {
    // 如果已经是字符串，直接处理
    let strValue = typeof value === 'string' ? value : String(value);
    
    // 移除多余空格
    strValue = strValue.trim();
    
    // 检查是否为JSON格式字符串
    if (strValue.startsWith('{') && strValue.endsWith('}')) {
      try {
        const parsed = JSON.parse(strValue);
        if (typeof parsed === 'object' && parsed !== null) {
          // 优先返回name属性
          if (parsed.name) return String(parsed.name);
          // 其次返回第一个非空值
          for (const key in parsed) {
            if (parsed[key]) {
              return String(parsed[key]);
            }
          }
        }
      } catch (e) {
        // JSON解析失败，继续处理
      }
    }
    
    // 处理JSON键值对片段，如 "name":"电影" 或 'name':'电影'
    const jsonKeyValuePattern = /["']([^"']+)["']\s*:\s*["']([^"']*)["']/;
    const match = strValue.match(jsonKeyValuePattern);
    if (match && match[2] !== undefined) {
      // 返回匹配的值部分，确保是string类型
      return match[2] ?? '';
    }
    
    // 移除可能的引号
    strValue = strValue.replace(/^["']|["']$/g, '');
    
    return strValue || defaultValue;
  } catch (error) {
    console.error('处理值失败:', error);
    return defaultValue;
  }
};

/**
 * 安全获取对象属性，处理可能的JSON字符串
 * @param obj 目标对象
 * @param prop 属性名
 * @param defaultValue 默认值
 * @returns 处理后的属性值或默认值
 */
const safeGetProp = (obj: any, prop: string, defaultValue: any) => {
  try {
    // 检查对象和属性是否存在
    if (!obj || typeof obj !== 'object' || !(prop in obj)) {
      return defaultValue;
    }
    
    let value = obj[prop];
    
    // 使用提取函数处理值
    return parseJsonValue(value, defaultValue);
  } catch (error) {
    console.error(`获取属性 ${prop} 失败:`, error);
    return defaultValue;
  }
};

/**
 * 格式化日期
 * @param dateString 日期字符串
 * @returns 格式化后的日期
 */
const formatDate = (dateString: string) => {
  try {
    const date = new Date(dateString);
    // 检查是否是有效日期
    if (isNaN(date.getTime())) {
      return '无效日期';
    }
    return date.toLocaleDateString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit' 
    });
  } catch (error) {
    return '无效日期';
  }
};

/**
 * 初始化用户数据
 */
const initData = () => {
  const userStr = localStorage.getItem('user');
  if (userStr) {
    userInfo.value = JSON.parse(userStr);
  }
};

/**
 * 加载所有视频类型数据
 */
const loadVideoTypes = async () => {
  loading.value = true;
  try {
    // 调用API获取视频类型数据
    console.log('开始获取视频类型数据');
    const response = await videoTypeService.getAllVideoTypes();
    console.log('获取视频类型响应:', response);
    
    if (response.code === 200) {
      videoTypes.value = response.data || [];
      console.log('视频类型数据:', videoTypes.value);
    } else {
      ElMessage.error(response.message || '获取视频类型失败');
      videoTypes.value = [];
    }
  } catch (error: any) {
    console.error('获取视频类型失败:', error);
    console.error('错误详情:', error.message, error.response);
    ElMessage.error('获取视频类型失败，请稍后重试');
    videoTypes.value = [];
  } finally {
    loading.value = false;
  }
};

/**
 * 退出登录
 */
const handleLogout = () => {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
  ElMessage.success('退出登录成功');
  router.push('/login');
};

/**
 * 打开添加视频类型对话框
 */
const handleAddVideoType = () => {
  // 重置表单数据
  Object.assign(editingVideoType, {
    type_id: undefined,
    name: '',
    description: ''
  });
  dialogVisible.value = true;
};

/**
 * 打开编辑视频类型对话框
 * @param videoType 要编辑的视频类型
 */
const handleEditVideoType = (videoType: VideoType) => {
  // 复制视频类型数据到编辑对象
  Object.assign(editingVideoType, { ...videoType });
  dialogVisible.value = true;
};

/**
 * 删除视频类型
 * @param videoType 要删除的视频类型
 */
const handleDeleteVideoType = async (videoType: VideoType) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除视频类型 "${videoType.name}" 吗？\n删除后数据将无法恢复。`, 
      '确认删除', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 调用API删除视频类型
    const response = await videoTypeService.deleteVideoType(videoType.type_id);
    
    if (response.code === 200) {
      // 从本地数据中移除
      const index = videoTypes.value.findIndex(vt => vt.type_id === videoType.type_id);
      if (index > -1) {
        videoTypes.value.splice(index, 1);
      }
      ElMessage.success(response.message || '删除成功');
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error: any) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      console.error('删除视频类型失败:', error);
      ElMessage.error('删除视频类型失败，请稍后重试');
    }
  }
};

/**
 * 保存视频类型（添加或更新）
 */
const handleSaveVideoType = async () => {
  if (!videoTypeFormRef.value) return;
  
  try {
    await videoTypeFormRef.value.validate();
    
    if (editingVideoType.type_id) {
      // 更新视频类型
      const response = await videoTypeService.updateVideoType(editingVideoType.type_id, {
        name: editingVideoType.name || '',
        description: editingVideoType.description || ''
      });
      
      if (response.code === 200) {
        // 更新本地数据
        const index = videoTypes.value.findIndex(vt => vt.type_id === editingVideoType.type_id);
        if (index > -1) {
          videoTypes.value[index] = response.data;
        }
        ElMessage.success(response.message || '更新成功');
        dialogVisible.value = false;
      } else {
        ElMessage.error(response.message || '更新失败');
      }
    } else {
      // 创建新视频类型
      const response = await videoTypeService.createVideoType({
        name: editingVideoType.name || '',
        description: editingVideoType.description || ''
      });
      
      if (response.code === 201 || response.code === 200) {
        // 添加到本地数据
        videoTypes.value.push(response.data);
        ElMessage.success(response.message || '创建成功');
        dialogVisible.value = false;
      } else {
        ElMessage.error(response.message || '创建失败');
      }
    }
    
    dialogVisible.value = false;
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('保存视频类型失败:', error);
      // 表单验证失败不需要额外提示
    }
  }
};

// 组件挂载时初始化数据
onMounted(() => {
  initData();
  loadVideoTypes();
});
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  background-color: #1a1a1a;
}

.sidebar {
  background-color: #2a2a2a;
  height: 100vh;
}

.logo {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #3a3a3a;
}

.logo h3 {
  color: #ffffff;
  margin: 0;
}

.el-menu-vertical-dark {
  background-color: transparent;
  border-right: none;
}

.el-menu-item {
  color: #cccccc;
  margin: 0 10px;
  border-radius: 4px;
}

.el-menu-item:hover {
  background-color: #3a3a3a;
  color: #ffffff;
}

.el-menu-item.is-active {
  background-color: #409eff;
  color: #ffffff;
}

.header {
  background-color: #2a2a2a;
  color: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #3a3a3a;
}

.user-info {
  margin-right: 20px;
  color: #cccccc;
}

.main-content {
  background-color: #1a1a1a;
  padding: 20px;
  overflow: auto;
  min-height: calc(100vh - 60px);
}

.management-content h2 {
  color: #ffffff;
  margin-bottom: 5px;
}

.section-title {
  color: #999999;
  margin-bottom: 20px;
  font-size: 14px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.video-types-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.video-type-card {
  background-color: #2a2a2a;
  border: none;
  border-radius: 8px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.video-type-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);
}

.video-type-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 15px;
}

.video-type-title h3 {
  color: #ffffff;
  margin: 0 0 5px 0;
  font-size: 18px;
}

.menu-button {
  cursor: pointer;
  z-index: 10;
  padding: 5px;
  border-radius: 4px;
}

.menu-button:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

/* 确保下拉菜单可点击 */
:deep(.el-dropdown-menu__item) {
  cursor: pointer;
  user-select: none;
}

:deep(.el-dropdown-menu__item):hover {
  background-color: #409eff;
  color: #ffffff;
}

.video-type-description {
  color: #cccccc;
  margin-bottom: 15px;
  font-size: 14px;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.video-type-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #3a3a3a;
}

.created-date,
.updated-date {
  color: #999999;
  font-size: 12px;
}

.empty-state {
  grid-column: 1 / -1;
  padding: 60px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 确保表单在深色模式下正常显示 */
:deep(.el-dialog__header) {
  background-color: #2a2a2a;
  border-bottom: 1px solid #3a3a3a;
}

:deep(.el-dialog__title) {
  color: #ffffff;
}

:deep(.el-dialog__body) {
  background-color: #2a2a2a;
  color: #cccccc;
}

:deep(.el-dialog__footer) {
  background-color: #2a2a2a;
  border-top: 1px solid #3a3a3a;
}

:deep(.el-input__wrapper),
:deep(.el-select__wrapper),
:deep(.el-textarea__wrapper) {
  background-color: #1a1a1a;
  border-color: #3a3a3a;
}

:deep(.el-input__inner),
:deep(.el-select__placeholder),
:deep(.el-textarea__inner) {
  color: #cccccc;
}

:deep(.el-form-item__label) {
  color: #cccccc;
}

:deep(.el-input__wrapper:hover),
:deep(.el-select__wrapper:hover),
:deep(.el-textarea__wrapper:hover) {
  border-color: #409eff;
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-select__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 1px rgba(64, 158, 255, 0.1);
}
</style>